import reportData from "./report-data";
function xhrAOP() {
  // 当前环境不支持xhr则退出
  if (!("XMLHttpRequest" in window)) return;

  const originalXhrProto = XMLHttpRequest.prototype;

  replaceAop(originalXhrProto, "open", function (originOpen) {
    return function (...args) {
      this._xhr = {
        method:
          typeof args[0] === "string" ? args[0].toLocaleUpperCase() : args[0],
        url: args[1],
        startTime: new Date().getTime(),
        type: "xhr",
      };

      originOpen.apply(this, args);
    };
  });

  replaceAop(originalXhrProto, "send", function (originSend) {
    return function (...args) {
      this.addEventListener("loadend", function () {
        const { responseType, status, response } = this;
        const endTime = new Date().getTime();
        this._xhr.reqData = args[0];
        this._xhr.status = status;
        if (["", "json", "text"].indexOf(responseType) !== -1) {
          this._xhr.reponseText =
            typeof response === "object" ? JSON.stringify(response) : response;
        }

        this._xhr.elapsedTime = endTime - this._xhr.startTime;

        reportData(this._xhr);
      });
    };
  });
}

function replaceAop(source, name, fn) {
  if (source === undefined) return;

  if (name in source) {
    const original = source[name];
    const wraped = fn(original);
    if (typeof wraped === "function") {
      source[name] = wraped;
    }
  }
}

export default xhrAOP

export {
	replaceAop,
}